/*
 * Copyright © OpenAtom Foundation.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.iec.edp.caf.databaseobject;

import io.iec.edp.caf.databaseobject.api.configuration.funcmapping.DBOFuncMappingLoader;
import io.iec.edp.caf.databaseobject.api.configuration.funcmapping.DatabaseFuncConfiguration;
import io.iec.edp.caf.databaseobject.api.configuration.funcmapping.DatabaseFuncMapping;

import java.io.IOException;

/**
 * @author liu_wei
 */
public class DatabaseFuncConverter extends DBOFuncMappingLoader {
    private static DatabaseFuncConverter instance;

    public DatabaseFuncConverter() throws IOException {
    }

    /**
     * 元数据序列化器帮助
     */

    public static DatabaseFuncConverter getInstance() {
        try {
            instance = (instance != null) ? instance : (instance = new DatabaseFuncConverter());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return instance;
    }

    public final boolean isExistConverMapping(String funcName) {
        DatabaseFuncConfiguration data = null;
        try {
            data = GetDatabaseObjectConfiguration(funcName);
        } catch (IOException e) {
            throw new RuntimeException("获取数据库对象函数映射配置报错", e);
        }
        if (data != null) {
            return true;
        } else {
            return false;
        }
    }

    public final String getFuncName(String GetFuncName, String dbType) {
        DatabaseFuncConfiguration data = null;
        try {
            data = GetDatabaseObjectConfiguration(GetFuncName);
        } catch (IOException e) {
            throw new RuntimeException("获取数据库对象函数映射配置报错", e);
        }
        if (data != null) {
            if (data.getDatabaseFuncMappings() != null && data.getDatabaseFuncMappings().size() > 0) {
                DatabaseFuncMapping funcMapping = data.getDatabaseFuncMappings().stream().filter((item) -> item.getDBType().equals(dbType)).findFirst().orElse(null);
                if (funcMapping.getFunc() != null && funcMapping.getFunc().length() > 0) {
                    return funcMapping.getFunc();
                }
            }
        }
        return GetFuncName;
    }
}
